package com.cts.tmall.biz.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cts.tmall.com.constant.UserStatus;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Lazy
@Slf4j
@Service
public class UserService extends BaseService<SysUser> {
    public SysUser login(String loginName, String password) {
        if (StringUtils.isAnyBlank(loginName, password)) {
            log.error("用户名、密码为空！");
            throw new SystemException(RspCode.FAILURE_LOGIN, "用户名密码不匹配");
        }
        SysUser user = getMapper().selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getLoginName, loginName));
        if (user == null) {
            log.error("用户名[{}]对应的用户不存在！", loginName);
            throw new SystemException(RspCode.FAILURE_LOGIN, "用户名密码不匹配");
        }
        if (!StringUtils.equals(DigestUtils.sha256Hex(password + user.getSalt()), user.getPassword())) {
            log.error("用户名[{}]与密码不匹配！", loginName);
            throw new SystemException(RspCode.FAILURE_LOGIN, "用户名密码不匹配");
        }
        if (StringUtils.equalsAny(user.getStatus(), UserStatus.DELETED, UserStatus.DISABLED)) {
            log.error("用户名[{}]对应的用户状态异常！", loginName);
            throw new SystemException(RspCode.FAILURE_LOGIN, "用户状态异常");
        }
        if (StringUtils.equalsAny(user.getStatus(), UserStatus.LOCKED)) {
            log.error("用户名[{}]对应的用户已锁定！", loginName);
            throw new SystemException(RspCode.FAILURE_LOGIN, "用户已锁定");
        }
        user.setToken(RandomStringUtils.randomAlphabetic(50));
        getMapper().updateById(user);
        return user;
    }

    public void registry(SysUser user) {

    }
}
